import 'package:flutter/material.dart';
import 'package:flutter_2b_client/apis/GoodsApi.dart';
import 'package:flutter_2b_client/components/EditGoodsForm.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:go_router/go_router.dart';

import '../components/GoodsUnitEditor.dart';

class EditGoodsPage extends HookWidget {
  const EditGoodsPage({required this.id, Key? key}) : super(key: key);
  static String path = "/goods/:id/edit";
  final int id;

  @override
  Widget build(BuildContext context) {
    var goodsDetailState = useState<GoodsDetail?>(null);
    useEffect(() {
      goodsApi.getGoodsDetail(id).then((value) {
        debugPrint(value.toString());
        goodsDetailState.value = value;
      });
      return null;
    }, [id]);
    return Scaffold(
      appBar: AppBar(title: const Text('编辑商品')),
      body: goodsDetailState.value == null
          ? Container()
          : EditGoodsForm(
              units: goodsDetailState.value!.units
                  .map((e) => GoodsUnitFormData(
                      name: e.name,
                      basicMultiple: e.basicMultiple,
                      id: e.id,
                      updatable: e.updatable))
                  .toList(),
              name: goodsDetailState.value!.name,
              barcode: goodsDetailState.value!.barcode,
              price: goodsDetailState.value!.price,
              amount: goodsDetailState.value!.amount,
              goodsBrandId: goodsDetailState.value!.brand?.id,
              goodsCategoryId: goodsDetailState.value!.category?.id,
              boxSpecification: goodsDetailState.value!.boxSpecification,
              recordFilingNumber: goodsDetailState.value!.recordFilingNumber,
              registrationCertificateNumber:
                  goodsDetailState.value!.registrationCertificateNumber,
              expressionPeriod: goodsDetailState.value!.expressionPeriod,
              note: goodsDetailState.value!.note,
              executiveStandard: goodsDetailState.value!.executiveStandard,
              onSave: (AddGoodsRequest request) async {
                await goodsApi.editGoods(
                  id,
                  request,
                );
                if (context.mounted) {
                  context.pop(true);
                }
              },
            ),
    );
  }
}
